from django.http import JsonResponse
from django.views.generic import View
from django.utils import timezone
from django.db.models import Q, F, Avg, Max, Min, Count, Sum
from app.RoleMethod.PublicMethod import PublicMethod
from app.models import *
import numpy


publicMethod = PublicMethod()


# --------------------------用户功能----------------------------
# 普通用户
class CheckTwoPasswords(View):
    """
    模块: 密码验证
    接口信息:
        GET:
            None
        POST:
            user_id: 用户账号
            password: 用户密码
    返回信息:
        GET:
            None
        POST:
            status: 验证状态[True|False](boolean)
            err: 提示信息
    """
    def get(self, request):
        pass

    def post(self, request):
        username = request.POST.get('user_id')
        password = request.POST.get('password')
        obj = Password.objects.filter(user_id=username)
        if obj.exists():
            obj = obj.first()
            if publicMethod.check_password(password_new=password, password_old=obj.password) or publicMethod.check_password2(password_new=password, password_old=obj.password):
                message = {'status': True, 'err': '验证通过'}
            else:
                message = {'status': False, 'err': '密码错误'}
        else:
            message = {'status': False, 'err': '用户验证失败'}
        return JsonResponse(message)


class Login(View):
    """
    模块: 用户登录
    接口信息:
        GET:
            None
        POST:
            user_id: 用户学号、工号
            password: 用户密码
            code: 图片验证码
    返回信息:
        GET:
            后台生成的验证码
        POST:
            status: 验证状态[True|False](boolean)
            err: 提示信息
            token: 登陆成功时的token
    """
    def get(self, request):
        res = publicMethod.capture(requester=request)
        return JsonResponse(res)

    def post(self, request):
        username = request.POST.get('user_id')
        password = request.POST.get('password')
        code = request.POST.get('code')
        if publicMethod.check_capture(requester=request, code=code):
            obj = Password.objects.filter(user_id=username)
            if obj.exists():
                obj = obj.first()
                if publicMethod.check_password(password_new=password, password_old=obj.password) or publicMethod.check_password2(password_new=password, password_old=obj.password):
                    user_obj = User.objects.filter(user_id=obj)
                    capacity = user_obj.first().role_pri if user_obj.exists() else 4
                    user_name = user_obj.first().real_name if user_obj.exists() else None
                    user_nick = user_obj.first().nick if user_obj.exists() else None
                    # print(capacity)
                    token = publicMethod.create_token({
                        'user_id': obj.user_id,
                        'capacity': capacity,
                        'user_name': user_name,
                        'user_nick': user_nick
                    }, 120)
                    LoginLog.objects.create(
                        user_id=username,
                        ip=publicMethod.get_ip(request),
                        time=timezone.now(),
                        login_way='JHCOJ'
                    )
                    massage = {'status': True, 'err': '登陆成功', 'token': token}
                else:
                    massage = {'status': False, 'err': '密码错误'}
            else:
                massage = {'status': False, 'err': '此用户未注册'}
        else:
            massage = {'status': False, 'err': '验证码错误'}
        return JsonResponse(massage)


class Register(View):
    """
    模块: 用户注册
    接口信息:
        GET:
            None
        POST:
            user_id: 用户学号、工号
            password: 用户密码
            check_pass: 重复密码
            code: 图片验证码
    返回信息:
        GET:
            后台生成的验证码
        POST:
            status: 验证状态[True|False](boolean)
            err: 提示信息
    """
    def get(self, request):
        res = publicMethod.capture(requester=request)
        return JsonResponse(res)

    def post(self, request):
        username = request.POST.get('user_id')
        password = request.POST.get('password')
        check_pass = request.POST.get('check_pass')
        code = request.POST.get('code')
        if publicMethod.check_capture(request, code):
            obj = Password.objects.filter(user_id=username)
            if obj.exists():
                state = {'status': False, 'err': '此用户已注册'}
            else:
                if password == check_pass:
                    Password.objects.create(user_id=username, password=publicMethod.reg_pass(password))
                    state = {'status': True, 'err': '注册成功'}
                else:
                    state = {'status': False, 'err': '密码输入不一致'}
        else:
            state = {'status': False, 'err': '验证码错误'}
        return JsonResponse(state)


class PerfectInfo(View):
    """
    模块: 用户信息获取，修改，完善
    接口信息:
        GET:
            token: token认证
        POST:
            token: token认证
            name: 用户姓名
            nickname: 用户昵称
            school: 用户所在学校
            sex: 用户性别{‘男’，‘女’}
    返回信息:
        GET:
            status: 数据请求状态
            err: 提示信息
            data: 用户个人的信息包
        POST:
            status: 验证状态[True|False](boolean)
            err: 提示信息
    """
    def get(self, request):
        token = request.GET.get('token')
        user_id = publicMethod.check_user_login(token)
        if not user_id:
            return JsonResponse({'status': False, 'err': '用户未登录'})
        obj = User.objects.filter(user_id__user_id=user_id)
        if obj.exists():
            messages = {'status': True, 'err': '个人用户信息', 'data': obj.values().first()}
        else:
            messages = {'status': False, 'err': '请先完善用户信息'}
        return JsonResponse(messages)

    def post(self, request):
        token = request.POST.get('token')
        user_id = publicMethod.check_user_login(token)
        if not user_id:
            return JsonResponse({'err': "用户认证失败"})
        real_name = request.POST.get('name')
        nick_name = request.POST.get('nickname')
        school = request.POST.get('school')
        sex = request.POST.get('sex')
        sex = (0 if sex == '男' else 1)
        user = Password.objects.get(user_id=user_id)
        obj = User.objects.filter(user_id=user)
        if obj.exists():
            obj = obj.first()
            if nick_name:
                obj.nick = nick_name
            if school:
                obj.school = school
            obj.ip = publicMethod.get_ip(request)
            obj.reg_time = timezone.now()
            obj.save()
            message = {'status': True, 'err': '信息修改成功'}
        else:
            User.objects.create(
                user_id=user,
                real_name=real_name,
                nick=nick_name,
                ip=publicMethod.get_ip(request),
                access_time=timezone.now(),
                reg_time=timezone.now(),
                school=school,
                sex=sex,
                role_pri=4,
                is_delete=0
            )
            message = {'status': True, 'err': '信息完善成功'}
        return JsonResponse(message)


class PasswordModification(View):
    """
    模块: 密码修改
    接口信息:
        GET:
            None
        POST:
            token: token认证
            old_password: 旧用户密码
            new_password: 新用户密码
            check_password: 重复密码
            code: 图片验证码
    返回信息:
        GET:
            后台生成的验证码
        POST:
            status: 请求状态[True|False](boolean)
            err: 提示信息
    """
    def get(self, request):
        res = publicMethod.capture(requester=request)
        return JsonResponse(res)

    def post(self, request):
        token = request.POST.get('token')
        user_id = publicMethod.check_user_login(token)
        if not user_id:
            return JsonResponse({'status': False, 'err': "用户认证失败"})
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        check_password = request.POST.get('check_password')
        code = request.POST.get('code')
        obj = Password.objects.get(user_id=user_id)
        if publicMethod.check_password(password_new=old_password, password_old=obj.password):
            if new_password == check_password:
                if publicMethod.check_capture(requester=request, code=code):
                    obj.password = publicMethod.reg_pass(new_password)
                    obj.save()
                    message = {'status': True, 'err': '密码修改成功'}
                else:
                    message = {'status': False, 'err': '验证码错误'}
            else:
                message = {'status': False, 'err': '密码输入不一致'}
        else:
            message = {'status': False, 'err': '密码错误'}
        return JsonResponse(message)


class SendEmail(View):
    """
    模块: 邮件发送,认证
    接口信息:
        GET:
            token: token认证（绑定邮箱时使用）
            user_id: 用户账号（找回密码时使用）
            email: 邮箱（绑定邮箱时使用）
        POST:
            token: token认证（绑定邮箱时使用）
            user_id: 用户账号（找回密码时使用）
            email: 邮箱（绑定邮箱时使用）
            code: 邮箱验证码
    返回信息:
        GET:
            status: 邮件发送状态
            err: 提示信息
        POST:
            status: 验证状态[True|False](boolean)
            err: 提示信息
    """
    def get(self, request):
        token = request.GET.get('token')
        user_id = request.GET.get('user_id')
        email = request.GET.get('email')
        if not token or not publicMethod.parse_payload(token).get('status'):
            obj = User.objects.filter(user_id__user_id=user_id)
            if not obj.exists():
                return JsonResponse({'status': False, 'err': '此用户未完善任何信息！！'})
            email = User.objects.get(user_id__user_id=user_id).email
            if not email:
                message = {'status': False, 'err': '邮箱未绑定'}
            else:
                if publicMethod.send_email(user_id, email):
                    message = {'status': True, 'err': '邮件发送成功', 'email': email}
                else:
                    message = {'status': False, 'err': '邮件发送失败', 'email': email}
        else:
            user_id = publicMethod.check_user_login(token)
            if user_id:
                if publicMethod.send_email(user_id, email):
                    message = {'status': True, 'err': '邮件发送成功', 'email': email}
                else:
                    message = {'status': False, 'err': '邮件发送失败', 'email': email}
            else:
                message = {'status': False, 'err': '用户认证失败'}
        return JsonResponse(message)

    def post(self, request):
        token = request.POST.get('token')
        user_id = request.POST.get('user_id')
        email = request.POST.get('email')
        code = request.POST.get('code')
        if not token or not publicMethod.parse_payload(token).get('status'):
            email = User.objects.get(user_id__user_id=user_id).email
            if publicMethod.check_email_code(email=email, code=code):
                message = {'status': True, 'err': '邮箱验证通过'}
                publicMethod.set_user_email(user_id + email)
            else:
                message = {'status': False, 'err': '邮箱验证失败'}
        else:
            user_id = publicMethod.check_user_login(token)
            if publicMethod.check_email_code(email=email, code=code):
                message = {'status': True, 'err': '邮箱绑定成功'}
                obj = User.objects.get(user_id__user_id=user_id)
                obj.email = email
                obj.save()
            else:
                message = {'status': False, 'err': '邮箱验证失败'}
        return JsonResponse(message)


class ForgetPassword(View):
    """
    模块: 忘记密码
    接口信息:
        GET:
            None
        POST:
            user_id: 用户账号
            new_password: 新用户密码
            check_password: 重复密码
            code: 图片验证码
    返回信息:
        GET:
            验证码内容
        POST:
            status: 验证状态[True|False](boolean)
            err: 提示信息
    """
    def get(self, request):
        res = publicMethod.capture(requester=request)
        return JsonResponse(res)

    def post(self, request):
        user_id = request.POST.get('user_id')
        new_password = request.POST.get('new_password')
        check_password = request.POST.get('check_password')
        code = request.POST.get('code')
        obj = Password.objects.get(user_id=user_id)
        if User.objects.filter(user_id=obj):
            user = User.objects.get(user_id=obj)
            if publicMethod.check_capture(requester=request, code=code):
                if new_password == check_password:
                    if publicMethod.check_user_email(user_id + user.email):
                        obj.password = publicMethod.reg_pass(new_password)
                        obj.save()
                        message = {'status': True, 'err': '密码重置成功'}
                    else:
                        message = {'status': False, 'err': '请先验证邮箱'}
                else:
                    message = {'status': False, 'err': '密码输入不一致'}
            else:
                message = {'status': False, 'err': '验证码错误'}
        else:
            message = {'status': False, 'err': '此用户信息未完善'}
        return JsonResponse(message)


class GetUserStatus(View):
    """
    模块: 获取用户状态
    接口信息:
        GET:
            user_id: 用户账号
        POST:
            None
    返回信息:
        GET:
            status: 邮件发送状态
            err: 提示信息
            user_id: 用户账号
            solved: 用户解决量
            submit: 用户提交量
            rank: 用户排名
            solution: 用户提交列表
            school: 用户所在学校
            solved_list: 用户已解决问题列表,
            submit_data: 用户提交数据（数据表使用）
            solved_data: 用户解决数据（数据表使用）
            date_data: 时间数据（数据表使用）
        POST:
            None
    """
    def __init__(self):
        super(GetUserStatus, self).__init__()
        self.year_now = timezone.now().year
        self.month_now = timezone.now().month
        self.day_now = timezone.now().day

    def get(self, request):
        user_id = request.GET.get('user_id')
        year = self.year_now - 1
        month = self.month_now
        day = 1 if self.day_now <= 15 else 15
        solution_list = []
        solved_list = []
        submit_data = []
        solved_data = []
        date_data = []
        user = User.objects.filter(user_id__user_id=user_id)
        solution = Solution.objects.filter(user_id=user_id)
        if user.exists():
            user = user.first()
            solved = user.solved
            submit = user.submit
            school = user.school
            rank = User.objects.filter(solved__gt=solved).count() + 1
            if solution.exists():
                stop = False
                while True:
                    begin_time = timezone.now().replace(year, month, day)
                    day += 15
                    if day == 31:
                        month += 1
                        day = 1
                        if month == 13:
                            month = 1
                            year += 1
                    end_time = timezone.now().replace(year, month, day)
                    if end_time >= timezone.now():
                        stop = True
                        end_time = timezone.now()
                    submit_data.append(solution.filter(in_date__range=[begin_time, end_time]).count())
                    solved_data.append(solution.filter(Q(result=4) & Q(in_date__range=[begin_time, end_time])).count())
                    date_data.append(end_time)
                    if stop:
                        break
                solution_list = solution.values("result").annotate(number=Count("user_id"))
                solved_list = solution.filter(result=4).values("problem_id").annotate(number=Count('user_id'))
                # print(len(solved_list), len(solution))
                user.solved = len(solved_list)
                user.submit = len(solution)
                user.save()
        else:
            return JsonResponse({'status': False, 'err': '输入用户不存在'})
        return JsonResponse({
                             'status': True,
                             'user_id': user_id,
                             'solved': solved,
                             'submit': submit,
                             'rank': rank,
                             'solution': list(solution_list),
                             'school': school,
                             'solved_list': list(solved_list),
                             'submit_data': list(submit_data),
                             'solved_data': list(solved_data),
                             'date_data': list(date_data)
                             })

    def post(self, request):
        pass


class GetRankList(View):
    """
    模块: 获取用户排名列表
    接口信息:
        GET:
            sort_by: 查询时间段[None|year|month|day](String)
        POST:
            search: 查询字段
    返回信息:
        GET:
            data: 用户排名列表
            data2: 用户排名列表（数据表使用）
        POST:
            data: 筛选后的用户排名列表
    """
    def get(self, request):
        sort_by = request.GET.get('sort_by')
        end_time = timezone.now()
        if sort_by == 'year':
            begin_time = f'{end_time.year - 1}-{end_time.month}-{end_time.day}'
            obj = publicMethod.get_rank_list_by_time(begin_time)
        elif sort_by == 'month':
            begin_time = f'{end_time.year}-{end_time.month - 1}-{end_time.day}'
            obj = publicMethod.get_rank_list_by_time(begin_time)
        elif sort_by == 'day':
            begin_time = f'{end_time.year}-{end_time.month}-{end_time.day - 1}'
            obj = publicMethod.get_rank_list_by_time(begin_time)
        else:
            obj = User.objects.all().order_by('-solved').values_list('user_id', 'real_name', 'nick', 'submit', 'solved', 'school', 'sex')
        data2 = list(obj)[:10]
        data2 = numpy.array(data2)
        data2 = data2.T
        return JsonResponse({"data": list(obj), "data2": data2.tolist()})

    def post(self, request):
        search = request.POST.get('search')
        obj = User.objects.filter(
            Q(user_id__user_id__contains=search) |
            Q(real_name__contains=search) |
            Q(nick__contains=search) |
            Q(school__contains=search)
        ).values('user_id', 'real_name', 'nick', 'submit', 'solved', 'school', 'sex')
        return JsonResponse({'data': list(obj)})


class GetUserTokenInfo(View):
    """
    模块: 获取用户权限信息
    接口信息:
        GET:
            token: 用户token
        POST:
            None
    返回数据:
        GET:
            用户token所包含信息
        POST:
            None
    """
    def get(self, request):
        token = request.GET.get('token')
        data = publicMethod.parse_payload(token)
        return JsonResponse(data)

    def post(self, request):
        pass


# 教师管理员功能
class GetUserList(View):
    """
    模块: 获取用户信息列表
    接口信息:
        GET:
            None
        POST:
            search: 查询字段
    返回信息:
        GET:
            data: 所有的用户列表
        POST:
            data: 筛选后的用户里列表
    """
    def get(self, request):
        obj = User.objects.all().values()
        return JsonResponse({"data": list(obj)})

    def post(self, request):
        search = request.POST.get('search')
        obj = User.objects.filter(
            Q(user_id__user_id__contains=search) |
            Q(real_name__contains=search) |
            Q(nick__contains=search) |
            Q(school__contains=search)
        )
        return JsonResponse({'data': list(obj)})


class ChangeUserCapacity(View):
    """
    模块: 修改用户权限
    接口信息:
        GET:
            None
        POST:
            token: 当前登录用户的token
            user: 要修改的用户id
            role_pri: 要修改的用户权限
    返回信息:
        GET:
            None
        POST:
            status: 数据操作状态
            err: 提示信息
    """
    def get(self, request):
        pass

    def post(self, request):
        token = request.POST.get('token')
        user_id = request.POST.get('user')
        role_pri = request.POST.get('role_pri')
        capacity = publicMethod.get_user_capacity(token)
        if capacity in [0, 1]:
            obj = User.objects.using('app').filter(user_id__user_id=user_id)
            if obj.exists():
                obj = obj.first()
                obj.role_pri = role_pri
                obj.save()
                message = {'status': True, 'err': '权限修改成功'}
            else:
                message = {'status': False, 'err': '未找到此用户'}
        else:
            message = {'status': False, 'err': '你未拥有此权限'}
        return JsonResponse(message)


class ResettingUserPassword(View):
    """
    模块: 重置用户密码
    接口信息:
        GET:
            None
        POST:
            token: 当前登录用户token
            user: 要修改的用户账号
            password: 修改后的密码
    返回信息:
        GET:
            None
        POST:
            status: 数据操作状态
            err: 提示信息
    """
    def get(self, request):
        pass

    def post(self, request):
        token = request.POST.get('token')
        user_id = request.POST.get('user')
        password = request.POST.get('password')
        capacity = publicMethod.get_user_capacity(token)
        if capacity in [0, 1]:
            obj = Password.objects.using('app').filter(user_id=user_id)
            if obj.exists():
                obj = obj.first()
                obj.password = publicMethod.reg_pass(password)
                obj.save()
                message = {'status': True, 'err': '密码修改成功'}
            else:
                message = {'status': False, 'err': '未找到此用户'}
        else:
            message = {'status': False, 'err': '你未拥有此权限'}
        return JsonResponse(message)


# -----------------------------------------------------------------------------------
class AddNews(View):
    def get(self, request):
        pass

    def post(self, request):
        title = request.POST.get('title')
        user_id = request.POST.get('user_id')
        content = request.POST.get('content')
        importance = request.POST.get('importance')
        image = request.POST.get('image')
        user_id = User.objects.get(user_id=user_id)
        obj = News.objects.create(
            user_id=user_id,
            title=title,
            content=content,
            time=timezone.now(),
            importance=importance,
            defunct=0,
            image=image
        )
        if obj:
            message = {'err': '创建成功'}
        else:
            message = {'err': '创建失败'}
        return JsonResponse(message)


# -------------------------------------竞赛功能-----------------------------------
# 沈斌鑫
# -------------------------------------论坛模块-----------------------------------
class CreateForm(View):
    """
        模块: 查看、创建论坛
        接口信息:
        GET:
            token: token认证
            page: 页数
        POST:
            token: token认证
            title: 标题
            description: 内容
    """
    def get(self, request):
        token = request.GET.get('token')
        page = int(request.GET.get('page', '1'))

        if not token:
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        user_id = publicMethod.check_user_login(token)
        identity = publicMethod.get_user_capacity(token)
        if not user_id:
            massage = {'err': 'No login'}
            return JsonResponse(massage, safe=False)
        else:
            user = User.objects.get(user_id__user_id=user_id)
            if not user:
                massage = {'err': 'No such user'}
                return JsonResponse(massage, safe=False)

        if identity not in [0, 1]:
            massage = {'err': 'No such user'}
            return JsonResponse(massage, safe=False)

        fs = FormSection.objects.all().order_by('create_time')[(page-1)*50:page*50]

        content_data = []
        for data in fs:
            content_data.append(
                {
                    'fs_id': data.fs_id,
                    'forum_section_title': data.forum_section_title,
                    'description': data.description,
                    'create_time': data.create_time,
                    'creator_nick': data.creator_nick,
                    'post_num': data.post_num,
                    'click_num': data.click_num,
                }
            )

        result = {'content': content_data, 'page': page}
        return JsonResponse(result, safe=False)

    def post(self, request):
        token = request.POST.get('token')
        title = request.POST.get('title')
        description = request.POST.get('description')

        if not (token and title and description):
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        user_id = publicMethod.check_user_login(token)
        identity = publicMethod.get_user_capacity(token)
        if not user_id:
            massage = {'err': 'No login'}
            return JsonResponse(massage, safe=False)
        else:
            user = User.objects.get(user_id__user_id=user_id)
            if not user:
                massage = {'err': 'No such user'}
                return JsonResponse(massage, safe=False)

        if identity not in [0, 1, 2]:
            massage = {'err': 'No such user'}
            return JsonResponse(massage, safe=False)

        FormSection.objects.create(
            forum_section_title=title,
            description=description,
            creator_id=user_id,
            creator_nick=user.nick,
            create_time=timezone.now(),
            function=0,
            is_delete=0,
        )

        massage = {'massage': '添加成功'}
        return JsonResponse(massage, safe=False)


class GetPostPage(View):
    """
    模块: 管理员/用户获取论坛页面。审核帖子
    接口信息:
    GET:
        fs_id: 论坛ID
        page: 页数
        types: 样式
    POST:
        token: token认证
        post_id: 帖子ID
        is_pass: 是否通过
        reason: 不通过理由
    """
    def get(self, request):
        fs_id = request.GET.get('fs_id')
        page = request.GET.get('page', '1')
        types = request.GET.get('types', '0')
        if page == '':
            page = '1'
        if types == '':
            types = '0'
        page = int(page)
        types = int(types)

        if fs_id:
            fs = FormSection.objects.filter(fs_id=int(fs_id)).first()
            if not fs:
                massage = {'err': '没有这个论坛'}
                return JsonResponse(massage, safe=False)

            fs.click_num = fs.click_num + 1
            fs.save()
            posts = Post.objects.filter(fs_id=fs_id, is_pass=1, function=0, is_delete=0).order_by("creator_time")[(page-1)*50:page*50]
        else:  # 管理员
            if types == 0:
                posts = Post.objects.filter(is_pass=1, function=0, is_delete=0).order_by("creator_time")[(page-1)*50:page*50]
            elif types == 1:
                posts = Post.objects.filter(is_pass=0, function=1, is_delete=0).order_by("creator_time")[(page-1)*50:page*50]
            elif types == 2:
                posts = Post.objects.filter(is_pass=0, function=1, is_delete=1).order_by("creator_time")[(page-1)*50:page*50]
            elif types == 3:
                posts = Post.objects.filter(is_pass=1, function=1, is_delete=1).order_by("creator_time")[(page-1)*50:page*50]
            else:
                massage = {'err': 'Type error'}
                return JsonResponse(massage, safe=False)
        
        post_data = []
        for data in posts:
            post_data.append(
                {
                    'post_id': data.post_id,
                    'post_title': data.post_title,
                    'content': data.content,
                    'creator': data.creator,
                    'creator_time': data.creator_time,
                    'creator_nick': data.creator_nick,
                    'likes_num': data.likes_num,
                    'comment_num': data.comment_num,
                    'collect_num': data.collect_num,
                    'reasons': data.reasons
                }
            )  
        
        massage = {'content': post_data, 'page': page}
        return JsonResponse(massage, safe=False)

    def post(self, request):
        token = request.POST.get('token')
        post_id = int(request.POST.get('post_id'))
        is_pass = request.POST.get('is_pass')
        reasons = request.POST.get('reasons')

        if not (token and post_id and is_pass):
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        user_id = publicMethod.check_user_login(token)
        identity = publicMethod.get_user_capacity(token)
        if not user_id:
            massage = {'err': 'No login'}
            return JsonResponse(massage, safe=False)
        else:
            user = User.objects.get(user_id__user_id=user_id)
            if not user:
                massage = {'err': 'No such user'}
                return JsonResponse(massage, safe=False)

        if identity not in [0, 1]:
            massage = {'err': 'No such user'}
            return JsonResponse(massage, safe=False)
        
        post = Post.objects.filter(post_id=post_id).first()
        if not post:
            massage = {'err': '帖子不存在'}
            return JsonResponse(massage, safe=False)

        fs = FormSection.objects.filter(fs_id=post.fs_id).first()
        print(is_pass)
        if int(is_pass) == 1:
            post.is_pass = 1
            post.function = 0
            post.is_delete = 0
            fs.post_num = fs.post_num + 1
        elif int(is_pass) == 0:
            if post.is_pass == 1:
                fs.post_num = fs.post_num - 1
            post.is_pass = 0
            post.function = 1
            post.is_delete = 1
        else:
            massage = {'err': '信息错误'}
            return JsonResponse(massage, safe=False)
        post.reasons = reasons
        post.save()
        fs.save()
        massage = {'massage': '审核过'}
        return JsonResponse(massage, safe=False)


class GetMyPost(View):
    """
    模块: 查看自己的帖子
    接口信息:
    GET:
        token: token认证
        types: 样式
    POST:
        None
    """
    def get(self, request):
        token = request.GET.get('token')
        types = request.GET.get('types')

        if not (token and types):
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        user_id = publicMethod.check_user_login(token)
        if not user_id:
            massage = {'err': 'No login'}
            return JsonResponse(massage, safe=False)
        else:
            user = User.objects.get(user_id__user_id=user_id)
            if not user:
                massage = {'err': 'No such user'}
                return JsonResponse(massage, safe=False)

        types = int(types)
        if types == 0:
            posts = Post.objects.filter(creator=user_id, is_pass=1, function=0, is_delete=0)
        elif types == 1:
            posts = Post.objects.filter(creator=user_id, is_pass=0, function=1, is_delete=0)
        elif types == 2:
            posts = Post.objects.filter(creator=user_id, is_pass=0, function=1, is_delete=1)
        elif types == 3:
            posts = Post.objects.filter(creator=user_id, is_pass=1, function=1, is_delete=1)
        else:
            massage = {'err': 'Type error'}
            return JsonResponse(massage, safe=False)

        post_data = []
        for data in posts:
            post_data.append(
                {
                    'post_id': data.post_id,
                    'post_title': data.post_title,
                    'content': data.content,
                    'reasons': data.reasons,
                    'creator_time': data.creator_time,
                }
            )
        
        massage = {'content': post_data}
        return JsonResponse(massage, safe=False)
        
    def post(self, request):
        massage = {'err': 'Wrong request method'}
        return JsonResponse(massage, safe=False)
        

class AddPost(View):
    """
    模块: 添加帖子
    接口信息:
    GET:
        None
    POST:
        token: token认证
        fs_id: 论坛ID
        title: 帖子标题
        content: 内容
    """
    def get(self, request):
        massage = {'err': 'Wrong request method'}
        return JsonResponse(massage, safe=False)

    def post(self, request):
        token = request.POST.get('token')
        fs_id = request.POST.get('fs_id')
        title = request.POST.get('title')
        content = request.POST.get('content')

        if not (token and fs_id and title and content):
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        user_id = publicMethod.check_user_login(token)
        if not user_id:
            massage = {'err': 'No login'}
            return JsonResponse(massage, safe=False)
        else:
            user = User.objects.get(user_id__user_id=user_id)
            if not user:
                massage = {'err': 'No such user'}
                return JsonResponse(massage, safe=False)

        fs = FormSection.objects.filter(fs_id=int(fs_id)).first()
        if not fs:
            massage = {'err': 'Wrong source'}
            return JsonResponse(massage, safe=False)

        Post.objects.create(
            fs_id=fs_id,
            post_title=title,
            content=content, 
            creator=user_id,
            creator_nick=user.nick,
            creator_time=timezone.now(), 
            likes_num=0, 
            comment_num=0, 
            collect_num=0, 
            is_pass=0,
            function=1,
            is_delete=0
        )

        massage = {'content': '添加成功'}
        return JsonResponse(massage, safe=False)


class DeletePost(View):
    """
    模块: 删除帖子
    接口信息:
    GET:
        None
    POST:
        token: token认证
        post_id: 帖子ID
    """
    def get(self, request):
        massage = {'err': 'Wrong request method'}
        return JsonResponse(massage, safe=False)

    def post(self, request):
        token = request.POST.get('token')
        post_id = int(request.POST.get('post_id'))

        if not (token and post_id):
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        user_id = publicMethod.check_user_login(token)
        identity = publicMethod.get_user_capacity(token)
        if not user_id:
            massage = {'err': 'No login'}
            return JsonResponse(massage, safe=False)
        else:
            user = User.objects.get(user_id__user_id=user_id)
            if not user:
                massage = {'err': 'No such user'}
                return JsonResponse(massage, safe=False)

        post = Post.objects.filter(post_id=post_id).first()
        if not post:
            massage = {'err': '帖子不存在'}
            return JsonResponse(massage, safe=False)

        if post.creator != user_id and identity not in [0, 1]:
            massage = {'err': 'User mismatch'}
            return JsonResponse(massage, safe=False)

        if post.is_delete == 1:
            massage = {'massage': '已删除'}
            return JsonResponse(massage, safe=False)

        fs = FormSection.objects.filter(fs_id=post.fs_id).first()
        if post.is_pass == 1:
            fs.post_num = fs.post_num - 1

        post.function = 1
        post.is_delete = 1
        post.save()

        content = {'content': 'Delete successfully'}
        return JsonResponse(content, safe=False)


class UndeletePost(View):
    """
    模块: 撤销删除帖子
    接口信息:
    GET:
        None
    POST:
        token: token认证
        post_id: 帖子ID
    """
    def get(self, request):
        massage = {'err': 'Wrong request method'}
        return JsonResponse(massage, safe=False)

    def post(self, request):
        token = request.POST.get('token')
        post_id = request.POST.get('post_id')

        if not (token and post_id):
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        user_id = publicMethod.check_user_login(token)
        identity = publicMethod.get_user_capacity(token)
        if not user_id:
            massage = {'err': 'No login'}
            return JsonResponse(massage, safe=False)
        else:
            user = User.objects.get(user_id__user_id=user_id)
            if not user:
                massage = {'err': 'No such user'}
                return JsonResponse(massage, safe=False)

        post = Post.objects.filter(post_id=int(post_id)).first()
        if not post:
            massage = {'err': '帖子不存在'}
            return JsonResponse(massage, safe=False)

        if post.creator != user_id and identity not in [0, 1]:
            massage = {'err': 'User mismatch'}
            return JsonResponse(massage, safe=False)

        post.is_pass = 0
        post.function = 1
        post.is_delete = 0
        post.save()

        massage = {'message': 'Modified successfully'}
        return JsonResponse(massage, safe=False)


class ModifyPost(View):
    """
    模块: 修改帖子
    接口信息:
    GET:
        token: token认证
        post_id: 帖子ID
    POST:
        token: token认证
        post_id: 帖子ID
        title:帖子标题
        content:内容
    """
    def get(self, request):
        token = request.GET.get('token')
        post_id = request.GET.get('post_id')

        if not (token and post_id):
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        user_id = publicMethod.check_user_login(token)
        identity = publicMethod.get_user_capacity(token)
        if not user_id:
            massage = {'err': 'No login'}
            return JsonResponse(massage, safe=False)
        else:
            user = User.objects.get(user_id__user_id=user_id)
            if not user:
                massage = {'err': 'No such user'}
                return JsonResponse(massage, safe=False)

        post = Post.objects.filter(post_id=int(post_id)).first()
        if not post:
            massage = {'err': '帖子不存在'}
            return JsonResponse(massage, safe=False)

        if post.creator != user_id and identity not in [0, 1]:
            massage = {'err': 'User mismatch'}
            return JsonResponse(massage, safe=False)

        content = {
            'post_id': post.post_id,
            'post_title': post.post_title,
            'content': post.content,
        }
        
        massage = {'content': content}
        return JsonResponse(massage, safe=False)
    
    def post(self, request):
        token = request.POST.get('token')
        post_id = request.POST.get('post_id')
        title = request.POST.get('title')
        content = request.POST.get('content')

        if not (token and post_id and title and content):
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        user_id = publicMethod.check_user_login(token)
        identity = publicMethod.get_user_capacity(token)
        if not user_id:
            massage = {'err': 'No login'}
            return JsonResponse(massage, safe=False)
        else:
            user = User.objects.get(user_id__user_id=user_id)
            if not user:
                massage = {'err': 'No such user'}
                return JsonResponse(massage, safe=False)

        post = Post.objects.filter(post_id=int(post_id)).first()
        if not post:
            massage = {'err': '帖子不存在'}
            return JsonResponse(massage, safe=False)

        if post.creator != user_id and identity not in [0, 1]:
            massage = {'err': 'User mismatch'}
            return JsonResponse(massage, safe=False)

        if post.post_title == title and post.content == content:
            massage = {'massage': '信息未修改'}
            return JsonResponse(massage, safe=False)
        
        post.post_title = title
        post.content = content
        post.is_pass = 0
        post.function = 1
        post.is_delete = 0
        post.save()

        content_date = {
            'post_id': post.post_id,
            'post_title': post.post_title,
            'content': post.content,
        }

        content = {'content': 'Modified successfully', 'post': content_date}
        return JsonResponse(content, safe=False)


class GetReplyPage(View):
    """
    模块: 查看帖子
    接口信息:
    GET:
        page: 页数
        fs_id: 论坛ID
        post_id: 帖子ID
    POST:
        None
    """
    def get(self, request):
        page = request.GET.get('page')
        fs_id = request.GET.get('fs_id')
        post_id = request.GET.get('post_id')

        if page == '':
            page = '1'

        if not(fs_id and post_id):
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        page = int(page)
        fs_id = int(fs_id)
        post_id = int(post_id)
        fs = FormSection.objects.filter(fs_id=fs_id).first()
        post = Post.objects.filter(post_id=post_id).first()
        if not (fs and post):
            massage = {'err': '论坛或帖子不存在'}
            return JsonResponse(massage, safe=False)

        replies = Reply.objects.filter(fs_id=fs_id, post_id=post_id, function=0).order_by("creator_time")[(page - 1) * 50:page * 50]

        post_data = {
            'post_id': post.post_id,
            'post_title': post.post_title,
            'content': post.content,
            'creator_nick': post.creator_nick,
            'creator_time': post.creator_time,
            'likes_num': post.likes_num,
            'comment_num': post.comment_num,
            'collect_num': post.collect_num,
        }

        reply_data = []
        for data in replies:
            reply_data.append(
                {
                    'reply_id': data.reply_id,
                    'content': data.content,
                    'creator': data.creator,
                    'creator_nick': data.creator_nick,
                    'creator_time': data.creator_time,
                }
            )

        result = {'post': post_data, 'reply': reply_data, 'page': page}
        return JsonResponse(result, safe=False)

    def post(self, request):
        massage = {'err': 'Wrong request method'}
        return JsonResponse(massage, safe=False)


class AddReply(View):
    """
    模块: 添加回复
    接口信息:
    GET:
        None
    POST:
        token: token认证
        fs_id: 论坛ID
        post_id: 帖子ID
        reply_id: 回复ID
        content: 内容
    """
    def get(self, request):
        massage = {'err': 'Wrong request method'}
        return JsonResponse(massage, safe=False)
    
    def post(self, request):
        token = request.POST.get('token')
        fs_id = request.POST.get('fs_id')
        post_id = request.POST.get('post_id')
        reply_id = request.POST.get('reply_id')
        content = request.POST.get('content')

        if reply_id == '':
            reply_id = '-1'

        if not(token and fs_id and post_id and content):
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        user_id = publicMethod.check_user_login(token)
        if not user_id:
            massage = {'err': 'No login'}
            return JsonResponse(massage, safe=False)
        else:
            user = User.objects.get(user_id__user_id=user_id)
            if not user:
                massage = {'err': 'No such user'}
                return JsonResponse(massage, safe=False)

        fs = FormSection.objects.filter(fs_id=int(fs_id)).first()
        post = Post.objects.filter(post_id=int(post_id)).first()

        if not (fs and post):
            massage = {'err': 'Wrong source'}
            return JsonResponse(massage, safe=False)
        
        Reply.objects.create(
            fs_id=int(fs_id),
            post_id=int(post_id),
            content=content,
            creator=user_id,
            creator_nick=user.nick,
            creator_time=timezone.now(),
            function=0,
            is_delete=0,
            to_reply_id=int(reply_id)
        )
        post.comment_num = post.comment_num + 1
        post.save()

        massage = {'content': '添加成功'}
        return JsonResponse(massage, safe=False)


class ModifyReply(View):
    """
    模块: 修改回复
    接口信息:
    GET:
        token: token认证
        reply_id: 回复ID
    POST:
        token: token认证
        reply_id: 回复ID
        content: 内容
    """
    def get(self, request):
        token = request.GET.get('token')
        reply_id = request.GET.get('reply_id')

        if not (token and reply_id):
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        user_id = publicMethod.check_user_login(token)
        identity = publicMethod.get_user_capacity(token)
        if not user_id:
            massage = {'err': 'No login'}
            return JsonResponse(massage, safe=False)
        else:
            user = User.objects.get(user_id__user_id=user_id)
            if not user:
                massage = {'err': 'No such user'}
                return JsonResponse(massage, safe=False)
            
        reply = Reply.objects.filter(reply_id=int(reply_id)).first()
        if not reply:
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        if reply.creator != user_id and identity not in [0, 1]:
            massage = {'err': 'Inconsistent users'}
            return JsonResponse(massage, safe=False)

        content = {
            'content': reply.content,
        }
        
        massage = {'content': content}
        return JsonResponse(massage, safe=False)

    def post(self, request):
        token = request.POST.get('token')
        reply_id = request.POST.get('reply_id')
        content = request.POST.get('content')

        if not (token and reply_id and content):
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        user_id = publicMethod.check_user_login(token)
        identity = publicMethod.get_user_capacity(token)
        if not user_id:
            massage = {'err': 'No login'}
            return JsonResponse(massage, safe=False)
        else:
            user = User.objects.get(user_id__user_id=user_id)
            if not user:
                massage = {'err': 'No such user'}
                return JsonResponse(massage, safe=False)

        reply = Reply.objects.filter(reply_id=reply_id).first()
        if not reply:
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        if reply.creator != user_id and identity not in [0, 1]:
            massage = {'err': 'Inconsistent users'}
            return JsonResponse(massage, safe=False)
        
        reply.content = content
        reply.save()

        massage = {'massage': 'Modified successfully'}
        return JsonResponse(massage, safe=False)


class DeleteReply(View):
    """
    模块: 删除回复
    接口信息:
    GET:
        None
    POST:
        token: token认证
        reply_id: 回复ID
    """
    def get(self, request):
        massage = {'err': 'Wrong request method'}
        return JsonResponse(massage, safe=False)
    
    def post(self, request):
        token = request.POST.get('token')
        reply_id = request.POST.get('reply_id')

        if not (token and reply_id):
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        user_id = publicMethod.check_user_login(token)
        identity = publicMethod.get_user_capacity(token)
        if not user_id:
            massage = {'err': 'No login'}
            return JsonResponse(massage, safe=False)
        else:
            user = User.objects.get(user_id__user_id=user_id)
            if not user:
                massage = {'err': 'No such user'}
                return JsonResponse(massage, safe=False)

        reply = Reply.objects.filter(reply_id=reply_id).first()
        if not reply:
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        if reply.creator != user_id and identity not in [0, 1]:
            massage = {'err': 'Inconsistent users'}
            return JsonResponse(massage, safe=False)

        post = Post.objects.filter(post_id=reply.post_id).first()

        if not post:
            massage = {'err': '帖子已经删了'}
            return JsonResponse(massage, safe=False)
        post.comment_num = post.comment_num - 1
        post.save()
        reply.function = 1
        reply.is_delete = 1
        reply.save()

        massage = {'massage': 'Modified successfully'}
        return JsonResponse(massage, safe=False)


class GetMyReply(View):
    """
    模块: 查看回复和删除自己帖子的回复
    接口信息:
    GET:
        token: token认证
    POST:
        token: token认证
        reply_id: 回复ID 
    """
    def get(self, request):
        token = request.GET.get('token')

        if not token:
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        user_id = publicMethod.check_user_login(token)
        if not user_id:
            massage = {'err': 'No login'}
            return JsonResponse(massage, safe=False)
        else:
            user = User.objects.get(user_id__user_id=user_id)
            if not user:
                massage = {'err': 'No such user'}
                return JsonResponse(massage, safe=False)

        content_data = []
        posts = Post.objects.filter(creator=user_id)
        for post in posts:
            replies = Reply.objects.filter(post_id=post.post_id, function=0)
            for reply in replies:
                content_data.append(
                    {
                        'reply_id': reply.reply_id,
                        'post_id': reply.post_id,
                        'content': reply.content,
                        'creator': reply.creator,
                        'creator_nick': reply.creator_nick
                    }
                )
        
        message = {'content': content_data}
        return JsonResponse(message, safe=False)

    def post(self, request):
        token = request.POST.get('token')
        reply_id = request.POST.get('reply_id')

        if not (token and reply_id):
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        user_id = publicMethod.check_user_login(token)
        if not user_id:
            massage = {'err': 'No login'}
            return JsonResponse(massage, safe=False)
        else:
            user = User.objects.get(user_id__user_id=user_id)
            if not user:
                massage = {'err': 'No such user'}
                return JsonResponse(massage, safe=False)
        
        reply = Reply.objects.filter(reply_id=int(reply_id)).first()
        post = Post.objects.filter(post_id=reply.post_id).first()

        if post.creator != user_id:
            massage = {'err': 'User without permission'}
            return JsonResponse(massage, safe=False)

        if reply.is_delete == 1:
            massage = {'massage': '这条回复已被删除'}
            return JsonResponse(massage, safe=False)

        post.comment_num = post.comment_num - 1
        post.save()
        reply.function = 1
        reply.is_delete = 1
        reply.save()
        
        massage = {'massage': 'Deleted successfully'}
        return JsonResponse(massage, safe=False)


class LikeCollection(View):
    """
    模块: 点赞收藏
    接口信息:
    GET:
        None
    POST:
        token: token认证
        post_id: 帖子ID
        types: 类型
    """
    def get(self, request):
        massage = {'err': 'Wrong request method'}
        return JsonResponse(massage, safe=False)
    
    def post(self, request):
        token = request.POST.get('token')
        post_id = request.POST.get('post_id')
        types = request.POST.get('types')

        if not(token and post_id and types):
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        user_id = publicMethod.check_user_login(token)
        if not user_id:
            massage = {'err': 'No login'}
            return JsonResponse(massage, safe=False)
        else:
            user = User.objects.get(user_id__user_id=user_id)
            if not user:
                massage = {'err': 'No such user'}
                return JsonResponse(massage, safe=False)

        post_id = int(post_id)
        content = PostUser.objects.filter(post_id=post_id, user_id=user_id).first()
        post = Post.objects.filter(post_id=post_id).first()

        if not post:
            massage = {'err': '帖子不存在！'}
            return JsonResponse(massage, safe=False)

        if not content:
            content = PostUser.objects.create(
                post_id=post_id,
                user_id=user_id,
                is_likes=0,
                is_collect=0,
            )
        
        if types == 'likes':
            if not content.is_likes:
                content.is_likes = 1
                post.likes_num = post.likes_num + 1
            else:
                content.is_likes = 0
                post.likes_num = post.likes_num - 1 
        elif types == 'collects':
            if not content.is_collect:
                content.is_collect = 1
                post.collect_num = post.collect_num + 1
            else:
                content.is_collect = 0
                post.collect_num = post.collect_num - 1
        else:
            massage = {'err': 'type error'}
            return JsonResponse(massage, safe=False)

        post.save()
        content.save()
        
        message = {'message': 'Like or Bookmark Success'}
        return JsonResponse(message, safe=False)
    

class GetPostCollect(View):
    """
    模块: 查看和删除论坛收藏
    接口信息:
    GET:
        token: token认证
    POST:
        token: token认证
        post_id: 帖子ID
    """
    def get(self, request):
        token = request.GET.get('token')

        if not token:
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        user_id = publicMethod.check_user_login(token)
        if not user_id:
            massage = {'err': 'No login'}
            return JsonResponse(massage, safe=False)
        else:
            user = User.objects.get(user_id__user_id=user_id)
            if not user:
                massage = {'err': 'No such user'}
                return JsonResponse(massage, safe=False)

        content = PostUser.objects.filter(user_id=user_id)

        content_data = []
        for data in content:
            if data.is_collect == 0:
                continue
            post = Post.objects.filter(post_id=data.post_id, function=0).first()
            content_data.append(
                {
                    'post_id': post.post_id,
                    'post_title': post.post_title,
                    'content': post.content,
                    'creator_nick': post.creator_nick,
                    'creator_time': post.creator_time,
                }
            )
        
        result = {'content': content_data}
        return JsonResponse(result, safe=False)

    def post(self, request):
        token = request.POST.get('token')
        post_id = request.POST.get('post_id')

        if not (token and post_id):
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)

        user_id = publicMethod.check_user_login(token)
        if not user_id:
            massage = {'err': 'No login'}
            return JsonResponse(massage, safe=False)
        else:
            user = User.objects.get(user_id__user_id=user_id)
            if not user:
                massage = {'err': 'No such user'}
                return JsonResponse(massage, safe=False)
        
        content = PostUser.objects.filter(post_id=int(post_id), user_id=user_id).first()
        post = Post.objects.filter(post_id=int(post_id)).first()

        if not content:
            massage = {'massage': '未收藏'}
            return JsonResponse(massage, safe=False)

        if not post:
            massage = {'err': '帖子不存在！'}
            return JsonResponse(massage, safe=False)

        if content.is_collect == 0:
            massage = {'massage': '未收藏'}
            return JsonResponse(massage, safe=False)

        content.is_collect = 0
        post.collect_num = post.collect_num - 1
        content.save()
        post.save()

        massage = {'massage': 'Modified successfully'}
        return JsonResponse(massage, safe=False)
